package webserver;

import java.util.ArrayList;
import java.util.Timer;

// <editor-fold defaultstate="collapsed" desc=" UML Marker "> 
// #[regen=yes,id=DCE.3606E1CA-7208-74AA-7467-3306DD1CBD09]
// </editor-fold>
/**
 * CacheManagement provides some functions to check the Cache
 * It will check for invalid entries and support PreCaching
 * 
 */
public class CacheManagement {

	// <editor-fold defaultstate="collapsed" desc=" UML Marker ">
	// #[regen=yes,id=DCE.49600874-6583-A7AF-2B5C-309A317B8B0B]
	// </editor-fold>
	// Variables
	private Cache cache;
	private Timer invTimer;
	private Timer preTimer;
	private CacheInvalidator cacheInv;
	private PreCaching preCache;
	private volatile ArrayList<Request> preCachedRequestList;

	// <editor-fold defaultstate="collapsed" desc=" UML Marker ">
	// #[regen=yes,id=DCE.31E3E2AB-ED6A-3CB3-A856-9AD989B98F1F]
	// </editor-fold>
	/**
	 * CacheManagement Default Constructor
	 * @param interval - Time in ms when CM performs tasks on the Cache
	 */
	public CacheManagement(int interval) {
		this.cache = Cache.getInstance();
		this.preCachedRequestList = new ArrayList<Request>();

		this.cacheInv = new CacheInvalidator();
		this.invTimer = new Timer("InvalidateCache", true);
		this.invTimer.scheduleAtFixedRate(this.cacheInv, interval, interval);

		this.preCache = new PreCaching(this);
		this.preTimer = new Timer("PreCachingTimer", true);
		this.preTimer.scheduleAtFixedRate(this.preCache, interval, interval);
	}

	/**
	 * Scan the given Request and preCache needed Resources
	 * @param re
	 */
	public synchronized void scanForPreCaching(Request re) {
		this.preCachedRequestList.add(re);
	}

	/**
	 * Get all Request which are waiting to be preCached
	 * @return all requests ready to be preCached
	 */
	public ArrayList<Request> getPreCachingRequests() {
		return this.preCachedRequestList;
	}
}

